// DOM元素
const elements = {
  apiKeyInput: document.getElementById('apiKey'),
  saveBtn: document.getElementById('saveBtn'),
  message: document.getElementById('message')
};

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async () => {
  // 加载已保存的API密钥
  await loadApiKey();
  
  // 绑定保存按钮事件
  elements.saveBtn.addEventListener('click', saveApiKey);
});

// 加载已保存的API密钥
async function loadApiKey() {
  try {
    const data = await chrome.storage.local.get('siliconFlowApiKey');
    if (data.siliconFlowApiKey) {
      elements.apiKeyInput.value = data.siliconFlowApiKey;
    }
  } catch (error) {
    showMessage('加载API密钥失败: ' + error.message, 'error');
  }
}

// 保存API密钥
async function saveApiKey() {
  const apiKey = elements.apiKeyInput.value.trim();
  
  if (!apiKey) {
    showMessage('请输入API密钥', 'error');
    return;
  }
  
  try {
    await chrome.storage.local.set({ siliconFlowApiKey: apiKey });
    showMessage('API密钥保存成功!', 'success');
    
    // 3秒后隐藏消息
    setTimeout(() => {
      hideMessage();
    }, 3000);
  } catch (error) {
    showMessage('保存API密钥失败: ' + error.message, 'error');
  }
}

// 显示消息
function showMessage(text, type) {
  elements.message.textContent = text;
  elements.message.className = 'message ' + type;
}

// 隐藏消息
function hideMessage() {
  elements.message.className = 'message';
}